<?php

namespace app\home\controller;

use think\Controller;
use think\Request;
use app\home\model\User as UserModel;

class User extends Controller
{
      //退出登录
     public function logout(){
         session('user_id', null);
         session('username', null);
         return $this->success('退出成功','/');
     }

     //登录
     public function login(Request $request){
          if($request->isPost()){
              //登录验证
              //省略验证步骤，自行完成
              $username=$request->post('username','','trim');
              $password=$request->post('password','','trim');
              $password=sha1($password);
              $userinfo=UserModel::where(['username'=>$username,'password'=>$password])->find();
              if(!$userinfo){
                  return $this->error('用户名或者密码输入错误');
              }
              $userinfo=$userinfo->toArray();
              //保存用户名字和id到session中
              session('user_id',$userinfo['id']);
              session('username',$userinfo['username']);
              return $this->success('登录成功','/');
          }else{
              //加载登录表单
              return $this->fetch();
          }
     }
     //注册
    public function register(Request $request){
        if($request->isPost()){
            //注册验证
            //省略验证步骤，自行完成
            $data=$request->post();
            $data['password']=sha1($data['password']);
            $user_model=new  UserModel();
            $res=$user_model->save($data);
            if($res){
                return $this->success('注册成功','login');
            }else{
                return $this->error('注册失败，请重新注册');
            }
        }else{
            //加载注册表单
            return $this->fetch();
        }
    }
}
